/**
 * 
 */
package com.ws.base.db.common;

import java.io.File;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;

import com.ws.base.common.util.WSUtil;
import com.ws.base.db.common.page.Page;
import com.ws.base.db.support.NamingXmlSupport;
import com.ws.base.exception.WSException;

/**
 * @author ewangshi
 */
public final class DBStartup implements ServletContextAware {

    public final void init() throws WSException {
        if (loadDBXml()) {
            System.out.println("loadDBXml success");
        } else {
            System.out.println("loadDBXml error");
        }
        loadDBType();
    }

    private final boolean loadDBXml() throws WSException {
        boolean flag = true;

        String path = application.getRealPath("WEB-INF" + File.separator
                + "conf");

        NamingXmlSupport namingXmlSupport = new NamingXmlSupport();
        namingXmlSupport.findNamingSqlFile(path);
        return flag;
    }

    private final void loadDBType() throws WSException {
        String path = application.getRealPath("WEB-INF" + File.separator
                + "conf" + File.separator + "jdbc.properties");
        PropertiesUtils utils = new PropertiesUtils(new File(path));
        String dbType = utils.getPropertiesValue("dbType");

        if (WSUtil.isEmpty(dbType)) {
            throw new WSException(
                    "NOT Found dbType, Please check jdbc.properties");
        } else {
            Page.pageType = dbType;
        }
    }

    public void setServletContext(ServletContext arg0) {
        application = arg0;
    }

    private ServletContext application;
}
